//
//  NKPlayingCell.m
//  NiKi
//
//  Created by qiang chen on 16/6/12.
//  Copyright © 2016年 qiang chen. All rights reserved.
//

#import "NKPlayingCell.h"
#import "CALayer+PauseAimate.h"
#define kLineWidth 10

@interface NKPlayingCell () {
    __weak IBOutlet UIView *_playV;
    CAShapeLayer *_progressLayer;
    CAShapeLayer *_backgroundLayer;
}

@end
@implementation NKPlayingCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupUI];
    [self addRotateAnimate];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}


- (void)applicationBecomeActive {
    [self addRotateAnimate];
}

- (void)setupUI {
    //翻转
    _playV.transform = CGAffineTransformMakeRotation(-M_PI_2);
    self.cDImageV.transform = CGAffineTransformMakeRotation(M_PI_2);
    _statusBtn.transform = CGAffineTransformMakeRotation(M_PI_2);

    //根据屏幕的大小改变图片
    _cDImageV.layer.cornerRadius = 250/667.f*ScreenH*0.5;
    
    //设置背景的layer
    _backgroundLayer = [CAShapeLayer layer];
    [_playV.layer addSublayer:_backgroundLayer];
    
    //设置进度条layer
    _progressLayer = [CAShapeLayer layer];
    [_playV.layer addSublayer:_progressLayer];
    _progressLayer.strokeEnd = 0;

}

- (CAShapeLayer *)setLayer:(CAShapeLayer *)layer layerColor:(UIColor *)color lineWidth:(CGFloat)width {
    CGRect rect = {kLineWidth*0.5,kLineWidth*0.5,_playV.width-kLineWidth,_playV.height-kLineWidth};
    
    //设置path
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
    layer.path = path.CGPath;
    
    //设置layer
    layer.strokeColor = color.CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = width;
    layer.lineCap = kCALineCapRound;
    
    return layer;
}

- (void)setProgress:(CGFloat)progress {
    _progress = progress;
    _progressLayer.strokeEnd = progress;
}

- (IBAction)playBtnClick:(UIButton *)sender {
    
    if (!sender.selected) {
        [_cDImageV.layer pauseAnimate];
    }else{
        [_cDImageV.layer resumeAnimate];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(NKPlayingCell:playStatusBtnClick:)]) {
        [self.delegate NKPlayingCell:self playStatusBtnClick:sender];
    }
}

- (void)addRotateAnimate {
    CABasicAnimation *animate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animate.fromValue = @(0);
    animate.toValue = @(M_PI * 2);
    animate.repeatCount = NSIntegerMax;
    animate.duration = 30.f;
    [_cDImageV.layer addAnimation:animate forKey:nil];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self setLayer:_backgroundLayer layerColor:[UIColor colorWithHex:0xff25231D] lineWidth:kLineWidth];
    [self setLayer:_progressLayer layerColor:MainColor lineWidth:kLineWidth];
}

@end
